package com.shycloud.mido.organ.api.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang.StringUtils;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import com.shycloud.mido.common.core.util.ClassUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class CodeUtil {
	
	private static final int QRCOLOR = 0xFF000000; // 默认是黑色
	private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色

	private static final int WIDTH = 400; // 二维码宽
	private static final int HEIGHT = 400; // 二维码高
	private static final String LOGO_32 = "http://file.formal.joymido.com/32.png";
	private static final String LOGO_64 = "http://file.formal.joymido.com/64.png";
	private static final String LOGO_96 = "http://file.formal.joymido.com/96.png";
	private static final String LOGO_128 = "http://file.formal.joymido.com/128.png";
	// 用于设置QR二维码参数
	private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
		private static final long serialVersionUID = 1L;
		{
			put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别（H为最高级别）具体级别信息
			put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
			put(EncodeHintType.MARGIN, 0);
		}
	};

	private static final String QR_CODE_IMAGE_PATH = null;

	public static String generateQRCodeImage(String text, int width, int height, String udid) throws WriterException, IOException {
		String file= ClassUtils.getDefaultClassLoader().getResource("").getPath();
		File upload = new File(file,"static/images/upload/"+udid+".png");
		System.out.println(upload.getAbsolutePath());
		if(!upload.exists()) {
			upload.mkdirs();
		}
		QRCodeWriter qrCodeWriter = new QRCodeWriter();

		BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

		Path path = FileSystems.getDefault().getPath(upload.getAbsolutePath());

		MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
		return upload.getAbsolutePath();
	}

//	public static void main(String[] args) {
//		try {
//			//String path = ResourceUtils.getURL("classpath:").getPath();
//			String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
//			File upload = new File(path,"static/images/upload/test.png");
//			System.out.println(upload.getAbsolutePath());
//			if(!upload.exists()) {
//				upload.mkdirs();
//			}
//			generateQRCodeImage("This is my first QR Code", 350, 350, upload.getAbsolutePath());
//			//System.out.println(	getQRCodeImage("This is my first QR Code", 350, 350));
//		} catch (WriterException e) {
//			System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
//		} catch (IOException e) {
//			System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
//		}
//
//	}

	public static byte[] getQRCodeImage(String text, int width, int height) throws WriterException, IOException {
		QRCodeWriter qrCodeWriter = new QRCodeWriter();
		BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

		ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
		MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
		byte[] pngData = pngOutputStream.toByteArray();
		return pngData;
	}

	// 生成带logo的二维码图片
	public static InputStream drawLogoQRCode(String qrUrl) {
		InputStream inputStream = null;
		try {
			MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
			// 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
			BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
			BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

			// 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
			for (int x = 0; x < WIDTH; x++) {
				for (int y = 0; y < HEIGHT; y++) {
					image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
				}
			}
//			int width = image.getWidth();
//			int height = image.getHeight();
//			if (logoFileUrl == null) {
//				logoFileUrl = LOGO_96;
//			}
//			URL urls = new URL(logoFileUrl);
//			if (Objects.nonNull(urls)) {
//				// 构建绘图对象
//				Graphics2D g = image.createGraphics();
//				// 读取Logo图片
//				BufferedImage logo = ImageIO.read(urls);
//				// 开始绘制logo图片
//				g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
//				g.dispose();
//				logo.flush();
//			}
//
//			// 自定义文本描述
//			if (StringUtils.isNotEmpty(note)) {
//				// 新的图片，把带logo的二维码下面加上文字
//				BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
//				Graphics2D outg = outImage.createGraphics();
//				// 画二维码到新的面板
//				outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
//				// 画文字到新的面板
//				outg.setColor(Color.BLACK);
//				outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号
//				int strWidth = outg.getFontMetrics().stringWidth(note);
//				if (strWidth > 399) {
//					// //长度过长就截取前面部分
//					// 长度过长就换行
//					String note1 = note.substring(0, note.length() / 2);
//					String note2 = note.substring(note.length() / 2, note.length());
//					int strWidth1 = outg.getFontMetrics().stringWidth(note1);
//					int strWidth2 = outg.getFontMetrics().stringWidth(note2);
//					outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
//					BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
//					Graphics2D outg2 = outImage2.createGraphics();
//					outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
//					outg2.setColor(Color.BLACK);
//					outg2.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
//					outg2.drawString(note2, 200 - strWidth2 / 2,outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
//					outg2.dispose();
//					outImage2.flush();
//					outImage = outImage2;
//				} else {
//					outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 画文字
//				}
//				outg.dispose();
//				outImage.flush();
//				image = outImage;
//			}

			image.flush();
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			ImageIO.write(image, "png", os);
			inputStream = new ByteArrayInputStream(os.toByteArray());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return inputStream;
	}

	// 生成带logo的二维码名片
	public static InputStream drawTeacherLogoQRCode(String logoFileUrl, String qrUrl, String teacherName, String orgName) {
		InputStream inputStream = null;

		try {
			ClassPathResource classPathResource = new ClassPathResource("simsun.ttc");
			InputStream fontInput = classPathResource.getInputStream();
			if (fontInput == null) {
				System.out.println("读取不到字体文件！");
				return null;
			}
			MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
			// 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
			BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
			BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

			// 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
			for (int x = 0; x < WIDTH; x++) {
				for (int y = 0; y < HEIGHT; y++) {
					image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
				}
			}

			int width = image.getWidth();
			int height = image.getHeight();
			if (logoFileUrl == null || StringUtils.isEmpty(logoFileUrl)) {
				logoFileUrl = LOGO_96;
			}
			URL urls = new URL(logoFileUrl);
			// 读取Logo图片
			BufferedImage logo = ImageIO.read(urls);
			if (Objects.nonNull(urls)) {
				// 构建绘图对象
				Graphics2D g = image.createGraphics();
				// 开始绘制logo图片
				g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
				g.dispose();
				logo.flush();
			}

			// 自定义文本描述
			if (StringUtils.isNotEmpty(orgName)) {
				// 新的图片，把带logo的二维码下面加上文字
				BufferedImage outImage = new BufferedImage(500, 800, BufferedImage.TYPE_4BYTE_ABGR);
				Graphics2D outg = outImage.createGraphics();
				outg.setColor(Color.white);
				outg.fillRect(0,0,500,800);
				// 画二维码到新的面板
				outg.drawImage(image, 50, 200, image.getWidth(), image.getHeight(), null);
				// 画头像到到新的面板
				outg.drawImage(logo, 40, 40, width * 2 / 10, height * 2 / 10, null);
				// 画文字到新的面板
				outg.setColor(Color.GRAY);
				Font baseFont = Font.createFont(Font.TRUETYPE_FONT, fontInput);
				Font font =baseFont.deriveFont(Font.BOLD, 16);

				outg.setFont(font); // 字体、字型、字号
				outg.drawString(orgName, 132, 95); // 画机构名称
				// 说明一
				String note1 = "扫描二维码图案，关联此教师";
				int strWidth1 = outg.getFontMetrics().stringWidth(note1);
				outg.drawString(note1, 250 - strWidth1 / 2, 160); // 画文字
				// 说明二
				String note2 = "欢迎使用听见咪哆APP";
				int strWidth2 = outg.getFontMetrics().stringWidth(note2);
				outg.drawString(note2, 250 - strWidth2 / 2, 650); // 画文字
				// 说明三
				String note3= "Appstore 或 应用宝 搜索'听见咪哆'下载并注册";
				int strWidth3 = outg.getFontMetrics().stringWidth(note3);
				outg.drawString(note3, 250 - strWidth3 / 2, 670); // 画文字
				// 说明四
				String note4= "扫码加入机构立即体验在线教育课";
				int strWidth4 = outg.getFontMetrics().stringWidth(note4);
				outg.drawString(note4, 250 - strWidth4 / 2, 690); // 画文字
				// 说明五
				String note5= "微信搜索听见'咪哆公众号'并关注,获取更多活动咨询";
				int strWidth5 = outg.getFontMetrics().stringWidth(note5);
				outg.drawString(note5, 250 - strWidth5 / 2, 730); // 画文字

				// 画教师姓名
				BufferedImage outImage2 = new BufferedImage(500, 800, BufferedImage.TYPE_4BYTE_ABGR);
				Graphics2D outg2 = outImage2.createGraphics();
				outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
				outg2.setBackground(Color.white);
				outg2.setColor(Color.BLACK);
				outg2.setFont(font); // 字体、字型、字号
				outg2.drawString(teacherName, 132,65);
				outg2.dispose();
				outImage2.flush();
				outImage = outImage2;
				outg.dispose();
				outImage.flush();
				image = outImage;
			}

			image.flush();
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			ImageIO.write(image, "png", os);
			inputStream = new ByteArrayInputStream(os.toByteArray());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return inputStream;
	}
}
